package com.wHitE.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.wHitE.utils.Result;
import com.wHitE.service.RegisterService;
import com.wHitE.service.impl.RegisterServiceImpl;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private RegisterService loginService = new RegisterServiceImpl();

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("注册接口初始化...");
        super.init(config);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("注册接口调用...");
        super.service(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取out对象
        PrintWriter out = resp.getWriter();

        //获取全部参数map
        //        Map<String, String[]> parameterMap = req.getParameterMap();
        //        Set<String> keySet = parameterMap.keySet();
        //        for (String key : keySet) {
        //            String[] values = parameterMap.get(key);
        //            System.out.println(key + ":");
        //            for (String value : values) {
        //                System.out.println(value + " ");
        //            }
        //        }

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String verificationCode = req.getParameter("verificationCode");

        // 初始化 object=>json 对象
        Gson gson = new Gson();

        //数据流获取信息
        StringBuilder stringBuilder = new StringBuilder();// 可变字符串构造对象
        BufferedReader reader = req.getReader();// 字符流读取对象
        char[] buf = new char[1024];// 创建字符数组(长度为请求体大小)
        int len;
        while ((len = reader.read(buf)) != -1) {// 追加字符串
            stringBuilder.append(buf, 0, len);
        }
        // 关闭字符输入流
        reader.close();
        // 将可变字符串转为字符串
        String str = stringBuilder.toString();

        String msg;

        if (username == null && password == null) {
            if (!str.isEmpty()) {
                //        // 以下方式通过创建类(属性与json对象的键值对应)接收请求的data参数值
                //        // 第一个参数需要json对象,第二个参数是对应的类
                //        Demo demo = gson.fromJson(str, Demo.class);
                //        System.out.println(demo.username + "," + demo.password);

                // 以下方式通过解析json字符串,获取参数值并转换为需要的数据类型
                // 实例化json解析对象
                JsonParser parser = new JsonParser();
                // 实例化json对象元素
                JsonElement element = parser.parse(str);
                // 获取并转换为所需的数据类型

                try {
                    username = element.getAsJsonObject().get("username").getAsString();
                    password = element.getAsJsonObject().get("password").getAsString();
                    email = element.getAsJsonObject().get("email").getAsString();
                    verificationCode = element.getAsJsonObject().get("verificationCode").getAsString();
                } catch (Exception e) {
                    out.print(gson.toJson(Result.error("请求体参数错误")));
                    return;
                }
            } else {
                out.print(gson.toJson(Result.error("路径参数错误")));
                return;
            }
        }
        Boolean isExpired = true;
        String verificationCode_Real = null;
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("email" + email.split("@")[0])) {
                verificationCode_Real = cookie.getValue();
                isExpired = false;
            }
        }
        if (!isExpired)
            if (verificationCode_Real.equals(verificationCode)) {
                msg = loginService.userRegister(username, email, password);
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("email" + email.split("@")[0])) {
                        cookie.setMaxAge(0);
                        resp.addCookie(cookie);
                    }
                }
            } else
                msg = "验证码错误";
        else
            msg = "验证码已过期";

        // 响应给前端
        if (msg.equals("success")) {
            out.print(gson.toJson(Result.success()));
        } else {
            out.print(gson.toJson(Result.error(msg)));
        }
    }

    @Override
    public void destroy() {
        System.out.println("注册接口关闭...");
    }
}
